package com.course.auth;

import com.course.domain.model.Account;
import com.course.domain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Created by Justin on 2017/5/18.
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Autowired
    public UserDetailsServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        Account account = userService.loadAccountByUsername(username);
        if (account == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        return User.withUsername(username).password(account.getPassword()).roles(account.getRole().getName()).build();
    }
}
